package com.example.ntpsynchronoustime.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author: njb
 * @date: 2023/7/3 23:45
 * @desc: 网络状态工具类
 */
public class NetworkUtil {
    private static final String TAG = NetworkUtil.class.getSimpleName();

    /**
     * ping的DNS
     */
    public static String[] dnsServiceIp = {"119.29.29.29", "8.8.8.8", "223.5.5.5", "223.6.6.6"};

    private static int index = 0;
    private static StringBuilder stringBuilder = new StringBuilder();

    private static volatile NetworkUtil mInStance;
    //  private StringBuilder stringBuilder = new StringBuilder();

    private NetworkUtil() {

    }

    public static NetworkUtil getInstance() {
        if (mInStance == null) {
            synchronized (NetworkUtil.class) {
                if (mInStance == null) {
                    mInStance = new NetworkUtil();
                }
            }
        }
        return mInStance;
    }

    /**
     * ping IP 地址
     * true ping 成功
     *
     * @return
     */
    public static String pingIp() {
        if (index == dnsServiceIp.length) {//外部有循环300次
            index = 0;
        }
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        Process process = null;
        while (index < dnsServiceIp.length) {
            try {
                String command = "ping -c 1 -w 2 " + dnsServiceIp[index];
                Log.d(TAG,"-----当前ping的ip------"+dnsServiceIp[index]);
                stringBuilder.setLength(0);
                Runtime runtime = Runtime.getRuntime();
                //-c 测试次数 -w 超时时间
                process = runtime.exec(command);
                int exitCode = process.waitFor();
                if (exitCode == 0) {//成功
                    Log.d("shell脚本文件执行成功:", String.valueOf(exitCode));
                    inputStreamReader = new InputStreamReader(process.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    index = 0;
                    return stringBuilder.append(stringBuilder).append("======").append(exitCode).toString();
                }
                index++;
                Log.d(TAG,"shell脚本文件执行失败:"+ exitCode);
            } catch (Exception e) {
                e.printStackTrace();
                index++;
                Log.e(TAG,"shell脚本执行错误"+ e.getMessage());
            } finally {
                try {
                    if (inputStreamReader != null) {
                        inputStreamReader.close();
                    }
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                  if (process != null) {
                        process.destroy();
                    }
                } catch (Exception io) {
                    io.printStackTrace();
                    Log.e("流文件关闭异常：", io.getMessage());
                }
            }
        }
        return "failed";
    }

    public String pingIp1() {
        if (index == dnsServiceIp.length) {//外部有循环300次
            index = 0;
        }
//        InputStreamReader inputStreamReader = null;
//        BufferedReader bufferedReader = null;
        Process proc = null;
        while (index < dnsServiceIp.length) {
            try {
                String command = "ping -c 1 -w 2 " + dnsServiceIp[index];
                Log.d(TAG,"-----当前ping的ip------"+dnsServiceIp[index]);
//                echo.setLength(0);
                Runtime runtime = Runtime.getRuntime();
                //-c 测试次数 -w 超时时间
                proc = runtime.exec(command);
                int exitCode = proc.waitFor();
                if (exitCode == 0) {//成功
                    Log.d(TAG,"shell脚本文件执行成功:"+exitCode);
//                    inputStreamReader = new InputStreamReader(proc.getInputStream());
//                    bufferedReader = new BufferedReader(inputStreamReader);
//                    String line;
//                    while ((line = bufferedReader.readLine()) != null) {
//                        echo.append(line).append("\n");
//                    }
                    index = 0;
                    return  "success";
                }else {
                    index++;
                    Log.e(TAG,"shell脚本文件执行失败:"+exitCode);
                    return  "failed";
                }

            } catch (Exception e) {
                e.printStackTrace();
                index++;
                Log.e(TAG,"shell脚本执行错误"+e.getMessage());
                return  "failed";
            } finally {
                try {
//                    if (inputStreamReader != null) {
//                        inputStreamReader.close();
//                    }
//                    if (bufferedReader != null) {
//                        bufferedReader.close();
//                    }
                    if (proc != null) {
                      //  proc.destroy();
                        Log.e(TAG,"====线程回收了===：" + proc.toString());
                    }
                } catch (Exception io) {
                    io.printStackTrace();
                    Log.e("流文件关闭异常：", io.getMessage());
                }
            }
        }
        return  "failed";
    }

    public void release() {
        if (stringBuilder != null) {
            stringBuilder = null;
        }
    }

    public boolean ping(String ipAddr, int times, StringBuffer output) {
        BufferedReader br = null;
        String cmd = "ping -c " + times + " " + ipAddr;
        Process process = null;
        boolean result = false;

        try {
            process = Runtime.getRuntime().exec(cmd);

            if (process == null) {
                appendLine(output, "ping fail:process is null.");
                return false;
            }

            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                appendLine(output, line);
            }

            if (process.waitFor() == 0) {
                appendLine(output, "exec cmd success:" + cmd);
                Log.d(TAG,"shell脚本文件执行成功:"+process.waitFor());
                result = true;
            } else {
                Log.e(TAG,"shell脚本执行s失败"+process.waitFor());

                appendLine(output, "exec cmd fail.");
            }
            appendLine(output, "exec finished.");

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG,"shell脚本执行错误"+e.getMessage());

            return false;
        } finally {
            if (process != null) {
                process.destroy();
                Log.e(TAG,"====线程回收了===：" + process.toString());
            }
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
                return result;
            }
        }
    }

    private static void appendLine(StringBuffer sb, String line) {
        if (sb != null) {
            sb.append(line + "\n");
        }
    }
}
